package com.git.dengchongshuang.managementsystem.menu;

import java.util.*;

//定义通讯录的主菜单所需的属性和方法
//接受用户输入并调用相应的功能
public class Menu {

    private final List<String> menuTitles = new ArrayList<String>();
    private final Map<String, MenuItem> menuItems = new LinkedHashMap<>();
    private static final Scanner scanner = new Scanner(System.in);

    private int menuWidth = 40;

    public Menu() {

    }

    public Menu(int menuWidth) {
        this();
        setMenuWidth(menuWidth);
    }

    public int getMenuWidth() {
        return menuWidth;
    }

    public void setMenuWidth(int menuWidth) {
        this.menuWidth = Math.max(menuWidth, 40);
    }

    public void addMenuTitle(String menuTitle) {
        menuTitles.add(menuTitle);
    }

    public  void addMenuItem(String menuValue, String keyStr, MenuCommand menuCommand) {
        if(menuItems.containsKey(keyStr)) {
            //如果keyStr已经存在，就什么都不做
        } else {
            MenuItem menuItem = new MenuItem(menuValue, menuCommand);
            menuItems.put(keyStr, menuItem);
        }
    }

    public void addMenuItem(MenuItem menu, String keyStr) {
        menuItems.put(keyStr, menu);
    }

    public Map<String, MenuItem> getMenuItems() {
        return menuItems;
    }

    public List<String> getMenuTitles() {
        return menuTitles;
    }

    // 获取用户输入，返回值用来给循环退出用的
    public void userInput() throws CloneNotSupportedException, BackException {
        String input = scanner.nextLine();
        if (menuItems.containsKey(input)) {
            menuItems.get(input).getCommand().executeCommand();
        }
    }

    public void userInput(String text) throws CloneNotSupportedException, BackException {
        System.out.println(text);
        userInput();
    }

    public void showMenuAndWaitForInput(String tipText) {
        while(true) {
            showMenu();
            try {
                userInput(tipText);
            } catch (BackException e) {
                break;
            } catch (CloneNotSupportedException e) {

            }
        }
    }

    public void showMenu() {
        for (String menuTitle : menuTitles) {
            System.out.println(menuTitle);
        }

        for (String menuItem : menuItems.keySet()) {
            // int lineLength = menuWidth - menuItem.length() * 2 - menuItems.get(menuItem).length() * 2 - 2;
            //System.out.println(" " + menuItem + " " + " ".repeat(lineLength) + " " + menuItems.get(menuItem));
            // 输出选项, 格式自定
            System.out.printf("%-10s%s%s\n", menuItem, " ".repeat(menuWidth - 10 - 30), menuItems.get(menuItem).getMenuValue());
        }
    }

    public static String input(String inputText) {
        System.out.println(inputText);
        return scanner.nextLine();
    }
}

